﻿using UnityEngine;
using System.Collections;

public class enemyUnit : MonoBehaviour {
	
	private GameObject[] limites;
	private float shootTime = 0;
	private float maxShootTime = 40;
	private float minshootTime = 2;
	private float zeroTime = 0;
	private Transform ownTransform;
	private bool shoot = false;
	private GameObject bala;
	private MeshRenderer renderer;
	// Use this for initialization
	void Start () {
		limites = new GameObject[2];
		limites [0] = GameObject.Find ("Limites/Derecha");
		limites [1] = GameObject.Find ("Limites/Izquierda");
		ownTransform = transform;
		renderer = gameObject.GetComponent ("MeshRenderer") as MeshRenderer;
		shootTimer ();
	}
	
	// Update is called once per frame
	void FixedUpdate () {
//		if (!shoot) {
//			shoot = canShoot ();
//		} else {
			if(Time.timeSinceLevelLoad - shootTime >= zeroTime){
				GameObject bala;
				bala = Instantiate(Resources.Load ("Prefabs/Bala")) as GameObject;
				(bala.GetComponent("Ammo") as Ammo).setOnPlayer(gameObject, new Vector3(0,-1,0));
				(bala.GetComponent("Ammo") as Ammo).setSpeed(-8f);
				(bala.GetComponent("Ammo") as Ammo).setLayer("AmmoEnemy");
				shootTimer();
			}
//		}
	}
	
	void OnDestroy(){
		if (limites [0] != null) {
			(limites [0].GetComponent ("screenLimit") as screenLimit).resetEnemies ();
		}
		if (limites [1] != null) {
			(limites [1].GetComponent ("screenLimit") as screenLimit).resetEnemies ();
		}
	}

	void shootTimer(){
		shootTime = Random.Range (minshootTime, maxShootTime);
		zeroTime = Time.timeSinceLevelLoad;
	}

	bool canShoot(){
		if (Physics.Raycast (ownTransform.position, Vector3.down, 100f, 1 << LayerMask.NameToLayer ("EnemySI"))) {
			return false;
		}
		return true;
	}

	void Shoot(){

	}
}
